<template>
  <div class="workflow-workbench">
    <div class="page-header">
      <h2>流程工作台</h2>
      <p>欢迎使用流程工作台，这里展示您的工作流相关信息</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid" v-auth="WorkflowAuth.WORKBENCH_LIST">
      <div class="stat-card">
        <div class="stat-icon">
          <Icon icon="ant-design:clock-circle-outlined" />
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ workbenchData.pendingTasks }}</div>
          <div class="stat-label">待办任务</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">
          <Icon icon="ant-design:play-circle-outlined" />
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ workbenchData.runningProcesses }}</div>
          <div class="stat-label">进行中流程</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">
          <Icon icon="ant-design:check-circle-outlined" />
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ workbenchData.completedProcesses }}</div>
          <div class="stat-label">已完成流程</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">
          <Icon icon="ant-design:file-text-outlined" />
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ workbenchData.myProcesses }}</div>
          <div class="stat-label">我发起的流程</div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 我的待办 -->
      <div class="content-section" v-auth="WorkflowAuth.TODO_LIST">
        <div class="section-header">
          <h3>我的待办</h3>
          <el-button 
            type="primary" 
            size="small" 
            @click="goToTodo"
            v-auth="WorkflowAuth.TODO_LIST"
          >
            查看全部
          </el-button>
        </div>
        <div class="task-list">
          <div 
            v-for="task in recentTasks" 
            :key="task.id" 
            class="task-item"
            v-auth="WorkflowAuth.TODO_PROCESS"
          >
            <div class="task-info">
              <div class="task-title">{{ task.taskName }}</div>
              <div class="task-process">{{ task.processName }}</div>
              <div class="task-time">{{ formatTime(task.createTime) }}</div>
            </div>
            <div class="task-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="processTask(task)"
                v-auth="WorkflowAuth.TODO_PROCESS"
              >
                处理
              </el-button>
            </div>
          </div>
          <div v-if="recentTasks.length === 0" class="empty-state">
            暂无待办任务
          </div>
        </div>
      </div>

      <!-- 流程动态 -->
      <div class="content-section" v-auth="WorkflowAuth.HISTORY_LIST">
        <div class="section-header">
          <h3>流程动态</h3>
          <el-button 
            type="primary" 
            size="small" 
            @click="goToHistory"
            v-auth="WorkflowAuth.HISTORY_LIST"
          >
            查看历史
          </el-button>
        </div>
        <div class="activity-list">
          <div 
            v-for="activity in recentActivities" 
            :key="activity.id" 
            class="activity-item"
          >
            <div class="activity-icon">
              <Icon :icon="getActivityIcon(activity.type)" />
            </div>
            <div class="activity-content">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-desc">{{ activity.description }}</div>
              <div class="activity-time">{{ formatTime(activity.time) }}</div>
            </div>
          </div>
          <div v-if="recentActivities.length === 0" class="empty-state">
            暂无流程动态
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions" v-auth="WorkflowAuth.PROCESS_START_LIST">
      <el-button 
        type="primary" 
        size="large" 
        @click="goToStartProcess"
        v-auth="WorkflowAuth.PROCESS_START_CREATE"
      >
        <Icon icon="ant-design:plus-outlined" />
        发起流程
      </el-button>
      <el-button 
        type="success" 
        size="large" 
        @click="goToMyProcess"
        v-auth="WorkflowAuth.MY_PROCESS_LIST"
      >
        <Icon icon="ant-design:file-text-outlined" />
        我的流程
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Icon from '@/components/Icon/Icon.vue'
import { ElMessage } from 'element-plus'
import { getWorkbenchData, getWorkbenchTasks } from '@/api/workflow/process.api'
import { WorkflowAuth } from '@/auth/workflow/workflow.auth'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

const router = useRouter()
const workbenchData = ref({
  pendingTasks: 0,
  runningProcesses: 0,
  completedProcesses: 0,
  myProcesses: 0
})
const recentTasks = ref([])
const recentActivities = ref([])

// 获取工作台数据
async function fetchWorkbenchData() {
  try {
    console.log('开始获取工作台数据')
    const response = await getWorkbenchData()
    console.log('工作台数据API响应:', response)
    
    if (response && response.data) {
      workbenchData.value = response.data
      console.log('获取到工作台数据:', workbenchData.value)
    } else if (response && response.code === 200) {
      workbenchData.value = response.data || {
        pendingTasks: 5,
        runningProcesses: 12,
        completedProcesses: 28,
        myProcesses: 8
      }
      console.log('使用API返回的工作台数据:', workbenchData.value)
    } else {
      console.log('API返回数据格式异常，使用默认数据')
      // 使用默认数据
      workbenchData.value = {
        pendingTasks: 5,
        runningProcesses: 12,
        completedProcesses: 28,
        myProcesses: 8
      }
    }
  } catch (error) {
    console.error('获取工作台数据失败:', error)
    ElMessage.warning('获取工作台数据失败，使用默认数据')
    // 使用默认数据
    workbenchData.value = {
      pendingTasks: 5,
      runningProcesses: 12,
      completedProcesses: 28,
      myProcesses: 8
    }
  }
}

// 获取最近任务
async function fetchRecentTasks() {
  try {
    console.log('开始获取最近任务')
    const response = await getWorkbenchTasks({ limit: 5 })
    console.log('工作台任务API响应:', response)
    
    if (response && response.data) {
      recentTasks.value = response.data
      console.log('获取到最近任务数量:', recentTasks.value.length)
    } else if (response && response.code === 200) {
      recentTasks.value = response.data || []
      console.log('使用API返回的最近任务数据:', recentTasks.value.length)
    } else {
      console.log('API返回数据格式异常，使用模拟数据')
      // 使用模拟数据
      recentTasks.value = [
        {
          id: 1,
          taskName: '审批请假申请',
          processName: '请假流程',
          assignee: 'admin',
          createTime: new Date().toISOString(),
          dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
          priority: 'HIGH'
        },
        {
          id: 2,
          taskName: '审核报销单',
          processName: '报销流程',
          assignee: 'admin',
          createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
          dueDate: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(),
          priority: 'MEDIUM'
        }
      ]
    }
  } catch (error) {
    console.error('获取最近任务失败:', error)
    ElMessage.warning('获取最近任务失败，使用模拟数据')
    // 使用模拟数据
    recentTasks.value = [
      {
        id: 1,
        taskName: '审批请假申请',
        processName: '请假流程',
        assignee: 'admin',
        createTime: new Date().toISOString(),
        dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
        priority: 'HIGH'
      },
      {
        id: 2,
        taskName: '审核报销单',
        processName: '报销流程',
        assignee: 'admin',
        createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        dueDate: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(),
        priority: 'MEDIUM'
      }
    ]
  }
}

// 获取流程动态
async function fetchRecentActivities() {
  try {
    console.log('开始获取流程动态')
    // 模拟流程动态数据
    recentActivities.value = [
      {
        id: 1,
        type: 'start',
        title: '张三发起了请假申请',
        description: '请假流程 - 请假3天',
        time: new Date(Date.now() - 30 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        type: 'approve',
        title: '李四审批通过',
        description: '请假流程 - 经理审批',
        time: new Date(Date.now() - 60 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        type: 'complete',
        title: '流程已完成',
        description: '报销流程 - 财务审核完成',
        time: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 4,
        type: 'delegate',
        title: '任务已委派',
        description: '采购流程 - 委派给王五',
        time: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString()
      }
    ]
    console.log('获取到流程动态数量:', recentActivities.value.length)
  } catch (error) {
    console.error('获取流程动态失败:', error)
    recentActivities.value = []
  }
}

// 处理任务
function processTask(task) {
  router.push({
    path: '/workflow/todo/process',
    query: { taskId: task.id }
  })
}

// 跳转到待办页面
function goToTodo() {
  router.push('/workflow/todo')
}

// 跳转到历史页面
function goToHistory() {
  router.push('/workflow/history')
}

// 跳转到发起流程页面
function goToStartProcess() {
  router.push('/workflow/start')
}

// 跳转到我的流程页面
function goToMyProcess() {
  router.push('/workflow/myProcess')
}

// 格式化时间
function formatTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return date.toLocaleDateString()
}

// 获取活动图标
function getActivityIcon(type) {
  const iconMap = {
    'start': 'ant-design:play-circle-outlined',
    'complete': 'ant-design:check-circle-outlined',
    'approve': 'ant-design:like-outlined',
    'reject': 'ant-design:dislike-outlined',
    'delegate': 'ant-design:user-switch-outlined'
  }
  return iconMap[type] || 'ant-design:info-circle-outlined'
}

onMounted(() => {
  fetchWorkbenchData()
  fetchRecentTasks()
  fetchRecentActivities()
})
</script>

<style scoped>
.workflow-workbench {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  margin-right: 16px;
  font-size: 32px;
  color: #409eff;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

.content-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.task-list, .activity-list {
  max-height: 400px;
  overflow-y: auto;
}

.task-item, .activity-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.task-item:last-child, .activity-item:last-child {
  border-bottom: none;
}

.task-info {
  flex: 1;
}

.task-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.task-process {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.task-time {
  font-size: 12px;
  color: #999;
}

.activity-item {
  display: flex;
  align-items: flex-start;
}

.activity-icon {
  margin-right: 12px;
  font-size: 16px;
  color: #409eff;
  margin-top: 2px;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.quick-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.quick-actions .el-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .quick-actions {
    flex-direction: column;
    align-items: center;
  }
}
</style> 